/*
 * Copyright 2013 floreysoft GmbH (www.floreysoft.net)
 *
 *
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 */
package com.floreysoft.gwt.drive.client.realtime;

import java.util.ArrayList;
import java.util.List;

import com.google.gwt.core.client.JsArray;

/**
 * A Realtime document. A document consists of a Realtime model and a set of
 * collaborators. Listen on the document for the following events:
 * 
 * gapi.drive.realtime.EventType.COLLABORATOR_LEFT
 * gapi.drive.realtime.EventType.COLLABORATOR_JOINED
 * gapi.drive.realtime.EventType.DOCUMENT_SAVE_STATE_CHANGED
 * 
 * This class should not be instantiated directly. The document object is
 * generated during the document load process.
 * 
 */
public final class Document extends EventTarget {

	protected Document() {

	}

	/**
	 * Gets the collaborative model associated with this document.
	 * 
	 * @return {@link Model}
	 */
	public native Model getModel()/*-{
		return this.getModel();
	}-*/;

	/**
	 * Closes the document and disconnects from the server. After this function
	 * is called, event listeners will no longer fire and attempts to access the
	 * document, model, or model objects will throw a
	 * {@link gapi.drive.realtime.DocumentClosedError}. Calling this function
	 * after the document has been closed will have no effect.
	 */
	public native void close() /*-{
		this.close();
	}-*/;

	/**
	 * Gets an array of collaborators active in this session. Each collaborator
	 * is a jsMap with these fields: sessionId, userId, displayName, color,
	 * isMe, isAnonymous.
	 * 
	 * @return A jsArray of collaborators.
	 */
	public List<Collaborator> getCollaborators(){
		List<Collaborator> values = new ArrayList<Collaborator>();
		JsArray<Collaborator> collaborators = internGetCollaborators();
		for(int i = 0; i < collaborators.length(); i++){
			Collaborator collaborator = collaborators.get(i);
			values.add(collaborator);
		}
		return values;
	}
	
	/**
	 * Interne JavaScript aufruf um die Collaborator des Document zu laden.
	 * @return JsArray mit {@link Collaborator}
	 */
	private native JsArray<Collaborator> internGetCollaborators() /*-{
		return this.getCollaborators();
	}-*/;

}
